package com.estronger.shopmanage.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.tu.loadingdialog.LoadingDailog;
import com.estronger.shopmanage.R;
import com.estronger.shopmanage.adapter.ItemFileAdapter;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.BeanImage;
import com.estronger.shopmanage.ui.othertask.bean.FileBean;
import com.estronger.shopmanage.utils.OpenFileUtil;
import com.estronger.shopmanage.utils.SDCardUtil;
import com.estronger.shopmanage.utils.Toast;
import com.google.gson.Gson;
import com.lidroid.xutils.http.RequestParams;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.DoubleUtils;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.soonfor.evaluate.activity.ShowPicActivity;
import com.soonfor.evaluate.bean.FileUploadBean;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class AddFileView extends LinearLayout{

    private Activity mContext;
    private LinearLayout ll_add_file;
    private TextView tv_file_title;
    private ImageView iv_add_file;//添加附件
    private RecyclerView rvfFiles;//附件

    private List<FileBean> localFiles = new ArrayList<>();//本地附件， 需要上传
    private List<FileBean> defaultFileList = new ArrayList<>();//（修改时）带入的已存在的附件列表
    private LinearLayoutManager fileManager;//附件manager
    private ItemFileAdapter fileAdapter;
    private EventListener listener;
    private boolean isCanEdit = false;//是否可编辑
    private LoadingDailog mLoadingDialog;
    private int _id;
    private Gson gson;

    public AddFileView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        View view = View.inflate(context, R.layout.view_addfiles, this);
        ll_add_file = view.findViewById(R.id.ll_add_file);
        tv_file_title = view.findViewById(R.id.tv_file_title);
        iv_add_file = view.findViewById(R.id.iv_add_file);
        rvfFiles = view.findViewById(R.id.rv_files);
    }
    /**
     * 初始化界面
     * @param activity
     */
    public void initView(Activity activity, int id, EventListener listener) {
        this.mContext = activity;
        this._id = id;
        this.listener = listener;
        this.gson = new Gson();
    }

    /**
     * 初始化附件view
     * @param title 标题
     * @param mLoadingDialog
     * @param isCanDelete 是否可以删除
     */
    public void initData(String title, LoadingDailog mLoadingDialog, boolean isCanDelete){
        tv_file_title.setText(title);
        this.mLoadingDialog = mLoadingDialog;
        this.isCanEdit = isCanDelete;
        fileManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        fileAdapter = new ItemFileAdapter(mContext, null, mLoadingDialog, isCanDelete);
        fileAdapter.setOnItemClick(new ItemFileAdapter.OnItemClick() {
            @Override
            public void onLongClickListener(View view, List<FileBean> fileBeans, int adapterposition) {
                removeFileAdapterItem(fileBeans, adapterposition);
            }
        });
        rvfFiles.setLayoutManager(fileManager);
        rvfFiles.setAdapter(fileAdapter);
        rvfFiles.setNestedScrollingEnabled(false);//禁止rcyc嵌套滑动
        iv_add_file.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!DoubleUtils.isFastDoubleClick())
                chooseFile(mContext, _id);
            }
        });
        if(isCanEdit)ll_add_file.setVisibility(VISIBLE);
        else ll_add_file.setVisibility(GONE);
        if (beforeFileMap == null) beforeFileMap = new HashMap<>();
        else beforeFileMap.clear();
    }

    //删除附件
    private void removeFileAdapterItem(List<FileBean> fileBeans, int adapterPosition) {
        FileBean fileBean = fileBeans.get(adapterPosition);
        for (int i = localFiles.size() - 1; i >= 0; i--) {
            if (localFiles.get(i).getAttachUrl().equals(fileBean.getAttachUrl())) {
                localFiles.remove(i);
            }
        }
        for (int j = defaultFileList.size() - 1; j >= 0; j--) {
            if (defaultFileList.get(j).getAttachUrl().equals(fileBean.getAttachUrl())) {
                defaultFileList.remove(j);
            }
        }
        //删除展示列表中的
        for(int k = fileBeans.size()-1; k >= 0; k--){
            if(fileBeans.get(k).getAttachUrl().equals(fileBean.getAttachUrl())){
                fileBeans.remove(k);
            }
        }
        fileAdapter.notifyDataSetChanged(fileBeans);
    }

    public void notifyDatas(List<FileBean> fileBeanList) {
        if (fileAdapter != null) fileAdapter.notifyDataSetChanged(fileBeanList);
    }
    //跳转去文件管理器中选择文件
    public void chooseFile(Activity activity, int requestCode) {
//        Uri uri = Uri.parse("content://com.android.externalstorage.documents/document/primary:");
//        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
//        intent.addCategory(Intent.CATEGORY_OPENABLE);
//        intent.setType("*/*");//想要展示的文件类型
//        intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, uri);
//        if(requestCode == 0)
//            activity.startActivityForResult(intent, CODE_CHOOSE_FILE);
//        else
//            activity.startActivityForResult(intent, requestCode);
          OpenFileUtil.chooseFile(activity, requestCode == 0 ? _id : requestCode);
    }
    /**
     * 计算结果个数
     */
    private int requestSuccessCount = 0;//成功
    private int requestFailCount = 0;//失败
    /**
     * 上传的附件url
     */
    private ArrayList<FileUploadBean> uploadFileUrls = new ArrayList<>();

    /**
     * 上传文件api
     */
    public void postFile() {
        requestSuccessCount = 0;
        requestFailCount = 0;
        if (uploadFileUrls == null) uploadFileUrls = new ArrayList<FileUploadBean>();
        else if (uploadFileUrls.size() > 0) uploadFileUrls.clear();
        if (localFiles != null && localFiles.size() > 0) {
            //上传附件
            for (FileBean fileBean : localFiles) {
                String path = fileBean.getAttachUrl();
                if (path.startsWith("http") || path.startsWith("D:")) {
                    //已上传的附件
                    if (beforeFileMap != null && beforeFileMap.size() > 0) {
                        for (Map.Entry<String, FileUploadBean> bMap : beforeFileMap.entrySet()){
                            if (path.contains(bMap.getKey())) {
                                uploadFileUrls.add(bMap.getValue());
                                break;
                            }
                        }
                    }
                    saveData(true, null, _id);
                }else {
                    //上传附件
                    File file = new File(path);
                    RequestParams forFile = new RequestParams();
                    forFile.addBodyParameter("usercode", MyApplication.getUserCode());
                    forFile.addBodyParameter("dir", "file");
                    forFile.addBodyParameter("imgFile", file);
                    listener.uploadFile(forFile, _id);
                }
            }
        }else {
            if (listener != null) {
                listener.afterUploadFile(uploadFileUrls, _id);
            }
        }
    }

    //附件上传成功
    public void uploadSuccess(int code, String result){
        FileUploadBean bean = gson.fromJson(result, FileUploadBean.class);
        // 进入activity时获取的同事信息
        if (bean.getError() == 0) {
            uploadFileUrls.add(bean);
        }
        saveData(true, "", code);
    }
    //附件上传失败
    public void uploadFail(int requestCode, String msg){
        saveData(false, msg, requestCode);
    }


    //更新附件View
    public void updateFilesRecyclerView(Activity activity, Intent data) {
        if (data == null) {
            // 用户未选择任何文件，直接返回
            return;
        }
        showLoadingDialog();
        String filePath = "";
        Uri uri = data.getData(); // 获取用户选择文件的URI
        if ("file".equalsIgnoreCase(uri.getScheme())){//使用第三方应用打开
            filePath = uri.getPath();
        }else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后
            filePath = getPathByUri4kitkat(mContext, uri);
        } else {//4.4以下下系统调用方法
            filePath = getRealPathFromURI(mContext, uri);
        }
        if(TextUtils.isEmpty(filePath))  filePath = data.getDataString();
        if(TextUtils.isEmpty(filePath)) return;
        String fname = "";
        if (filePath == null || filePath.length() == 0) {
            Toast.show(mContext, "附件路径为空!", Toast.LENGTH_SHORT);
            closeLoadingDialog();
            return;
        }
        try {
            filePath = URLDecoder.decode(filePath, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (!filePath.startsWith("/storage") && filePath.contains("emulated/0/")) {
            String rPath = filePath.substring(filePath.indexOf("/emulated/0/"));
            filePath = "/storage" + rPath;
        }
        File file = new File(filePath);
        fname = file.getName();
        long fsize = 0;
        if (!filePath.contains("HomeCase/")) {
            String tmpPath = SDCardUtil.SDCardRoot + "HomeCase/" + fname;//临时存储路径
            boolean isSuccessful = SDCardUtil.copyFileToTagDir(file.getAbsolutePath(), tmpPath);
            if (isSuccessful) {
                filePath = tmpPath;
                fsize = getFileSize(new File(tmpPath));
            } else {
                fsize = getFileSize(file);
            }
        }else fsize = getFileSize(file);
        if (fsize > 0 && fsize < 30 * 1024 * 1000) {
            FileBean fileBean = new FileBean("0", filePath, fname);
            if (localFiles == null) localFiles = new ArrayList<>();
            boolean isExsit = false;
            for (FileBean fb : localFiles) {
                if (fb.getAttachUrl().equals(fileBean.getAttachUrl())) {
                    isExsit = true;
                    break;
                }
            }
            if (!isExsit) {
                localFiles.add(fileBean);
            }
            List<FileBean> fileBeanList = new ArrayList<>();
            fileBeanList.addAll(defaultFileList);
            fileBeanList.addAll(localFiles);
            fileAdapter.notifyDataSetChanged(fileBeanList);
            closeLoadingDialog();
        }else {
            closeLoadingDialog();
            if (fsize == 0) {
                Toast.show(mContext, "文件大小为0，添加无效!", Toast.LENGTH_SHORT);
            }else {
                Toast.show(mContext, "所选文件大小不可超过30M", Toast.LENGTH_SHORT);
            }
            return;
        }
    }
    private Map<String, FileUploadBean> beforeFileMap;//修改前的已上传的附件
    //更新已有的网络图片
    public void updateNetImages(List<FileBean> netUrls, Map<String, FileUploadBean> fFileMap) {
        localFiles = new ArrayList<>(); //group2/M00/00/CA/wKgaxWG79XCAdrCEAAAYqUUyT-A108.mp3
        localFiles.addAll(netUrls);
        this.beforeFileMap = fFileMap;
        fileAdapter.notifyDataSetChanged(localFiles);
    }

    public String getRealPathFromURI(Context context, Uri contentUri) {
        String res = null;
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        if(null!=cursor&&cursor.moveToFirst()){
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
            cursor.close();
        }
        return res;
    }

    @SuppressLint("NewApi")
    public static String getPathByUri4kitkat(final Context context, final Uri uri) {
        try {
            final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
            if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
                if (isExternalStorageDocument(uri)) {// ExternalStorageProvider
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];
                    if ("primary".equalsIgnoreCase(type)) {
                        return SDCardUtil.SDCardRoot + split[1];
                    }
                } else if (isDownloadsDocument(uri)) {// DownloadsProvider
                    final String id = DocumentsContract.getDocumentId(uri);
                    if(id.startsWith("raw:")) {
                        return id.substring(id.indexOf(":")+1);
                    }
                    final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                            Long.valueOf(id));
                    return getDataColumn(context, contentUri, null, null);
                } else if (isMediaDocument(uri)) {// MediaProvider
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];
                    Uri contentUri = null;
                    if ("image".equals(type)) {
                        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if ("video".equals(type)) {
                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("audio".equals(type)) {
                        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }
                    final String selection = "_id=?";
                    final String[] selectionArgs = new String[] { split[1] };
                    return getDataColumn(context, contentUri, selection, selectionArgs);
                }
            } else if ("content".equalsIgnoreCase(uri.getScheme())) {// MediaStore
                // (and
                // general)
                return getDataColumn(context, uri, null, null);
            } else if ("file".equalsIgnoreCase(uri.getScheme())) {// File
                return uri.getPath();
            }
        }catch (Exception e){
            e.fillInStackTrace();
        }
        return null;
    }
    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = { column };
        try {
            try{
                cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            }catch (Exception e) {}
            if (cursor != null && cursor.moveToFirst()) {
                try {
                    final int column_index = cursor.getColumnIndexOrThrow(column);
                    return cursor.getString(column_index);
                }catch (Exception e){}
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public long getFileSize(File f) {
        long size = 0;
        if (f.exists() && f.isFile()) {
            size = f.length();
        }
        return size;
    }


    public synchronized void saveData(boolean isSuccess, String msg, int requestCode) {
        if (isSuccess)
            requestSuccessCount++;
        else {
            requestFailCount++;
        }
        if (requestSuccessCount + requestFailCount == localFiles.size()) {
            //如果全部请求都返回
            if (requestFailCount > 0) {
                PictureFileUtils.deleteCacheDirFile(mContext);
                requestFailCount = 0;
                Toast.show(mContext, "附件上传失败" + (TextUtils.isEmpty(msg) ? "" : ":" + msg), Toast.LENGTH_SHORT);
                closeLoadingDialog();
            } else {
                requestSuccessCount = 0;
                if (listener != null)listener.afterUploadFile(uploadFileUrls, requestCode);
            }

        }
    }

    public interface EventListener {
        void uploadFile(RequestParams params, int requestCode);//上传附件
        void afterUploadFile(ArrayList<FileUploadBean> fileUploadBeans, int requestCode);//上传附件成功后
    }

    public void showLoadingDialog() {
        if (mLoadingDialog != null && !mLoadingDialog.isShowing()) {
            mLoadingDialog.show();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    closeLoadingDialog();
                }
            }, 60000);
        }
    }

    public void closeLoadingDialog() {
        mContext.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
                    try {
                        mLoadingDialog.dismiss();
                    }catch (Exception e){}
                }
            }
        });
    }

}
